package com.palmar.proxy.server;

import com.palmar.proxy.configuration.SocksProxyConfiguration;
import com.palmar.proxy.initial.SocksProxyChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class SocksServerStarter extends ProxyStarter{


    private NioEventLoopGroup bossGroup;

    private NioEventLoopGroup workerGroup;

    private ServerBootstrap serverBootstrap;//提供TCP接入 代理

    private Bootstrap bootstrap;//用于TCP连接remote

    private Bootstrap  udpBootstrap;//用于udp发送和接收

    private SocksProxyConfiguration configuration;

    private Bootstrap forwardBootStrap;

    private static Logger logger = LoggerFactory.getLogger(SocksServerStarter.class);

    @Autowired
    public SocksServerStarter(SocksProxyConfiguration configuration, Bootstrap forwardBootStrap) {
        this.configuration = configuration;
        this.forwardBootStrap = forwardBootStrap;
        this.init();
    }

    @Override
    protected void init() {
        //初始化线程组
        this.bossGroup = new NioEventLoopGroup(this.configuration.bossEventLoopGroupCount);
        this.workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
        //TCP服务端
        this.serverBootstrap = new ServerBootstrap();
        this.serverBootstrap.channel(NioServerSocketChannel.class);
        this.serverBootstrap.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption
                .SO_KEEPALIVE, true);
        this.serverBootstrap.childHandler(new SocksProxyChannelInitializer());


        //tcp客户端
        this.bootstrap = new Bootstrap();
        this.bootstrap.channel(NioSocketChannel.class);
        this.bootstrap.group(this.workerGroup);

        //udp客户端 和 服务端
        this.udpBootstrap = new Bootstrap();
        this.udpBootstrap.channel(DatagramChannel.class);
        this.udpBootstrap.group(this.workerGroup);
        this.udpBootstrap.option(ChannelOption.SO_KEEPALIVE.SO_BACKLOG, 100);




    }

    @Override
    public ServerBootstrap start() {
        try {
            ChannelFuture future = this.serverBootstrap.bind(this.configuration.tcpPort).sync();
            logger.info("服务启动在[{}]端口", this.configuration.tcpPort);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
        return this.serverBootstrap;
    }
}
